package com.rongji.egov.fileupload.s3.web;

import com.rongji.egov.fileupload.s3.domain.Result;
import com.rongji.egov.fileupload.s3.utils.ConvertOp;
import com.rongji.egov.fileupload.s3.utils.S3Util;
import com.rongji.egov.fileupload.s3.utils.StringUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
@RestController
@RequestMapping("/s3")
public class FileUploadController {
    @Resource
    private S3Util s3Util;

    @GetMapping("/")
    public ResponseEntity<String> listBuckets() throws Exception {
        String xml = "";
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("ListAllMyBucketsResult");
        Element owner = root.addElement("Owner");
        Element id = owner.addElement("ID");
        id.setText("20230529");
        Element displayName = owner.addElement("DisplayName");
        displayName.setText("admin");
        Element buckets = root.addElement("Buckets");
        for (int i=0 ; i< 1; i++) {
            Element bucket = buckets.addElement("Bucket");
            Element name = bucket.addElement("Name");
            name.setText(i + "");
            Element creationDate = bucket.addElement("CreationDate");
            creationDate.setText(i + "");
        }
        OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        StringWriter out;
        out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        writer.close();
        xml = out.toString();
        out.close();
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xml);
    }

    @PutMapping("/{bucketName}/**")
    public ResponseEntity<String> putObject(@PathVariable String bucketName, HttpServletRequest request) throws Exception {
        bucketName = URLDecoder.decode(bucketName, "utf-8");
        String pageUrl = URLDecoder.decode(request.getRequestURI(), "utf-8");
        if (pageUrl.indexOf("\\?") >= 0) {
            pageUrl = pageUrl.split("\\?")[0];
        }
        String objectKey = pageUrl.replace(request.getContextPath() + "/s3/" + bucketName + "/", "");

       s3Util.upload(objectKey, request.getInputStream());
       return ResponseEntity.ok().build();

    }

    @GetMapping("/{bucketName}/**")
    public void getObject(@PathVariable String bucketName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        bucketName = URLDecoder.decode(bucketName, "utf-8");
        String pageUrl = URLDecoder.decode(request.getRequestURI(), "utf-8");
        if (pageUrl.indexOf("\\?") >= 0) {
            pageUrl = pageUrl.split("\\?")[0];
        }
        String objectKey = pageUrl.replace(request.getContextPath() + "/s3/" + bucketName + "/", "");
        byte[] datas = s3Util.getFile(objectKey);
        //response.setContentType(objectStream.getMetadata().getContentType());
        response.setHeader("Content-Disposition", "filename=" + objectKey);
        response.setCharacterEncoding("utf-8");
        response.setContentLength(ConvertOp.convert2Int(datas.length));
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(datas));
            int i = 0;
            byte[] buff = new byte[1024];
            while ((i = bufferedInputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, i);
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @DeleteMapping("/{bucketName}/**")
    public ResponseEntity<String> deleteObject(@PathVariable String bucketName, HttpServletRequest request) throws Exception {
        bucketName = URLDecoder.decode(bucketName, "utf-8");
        String pageUrl = URLDecoder.decode(request.getRequestURI(), "utf-8");
        if (pageUrl.indexOf("\\?") >= 0) {
            pageUrl = pageUrl.split("\\?")[0];
        }
        String objectKey = pageUrl.replace(request.getContextPath() + "/s3/" + bucketName + "/", "");
        s3Util.deleteFile(objectKey);
        return ResponseEntity.noContent().build();
    }
}
